package sentinel.demo.test;

import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;


public class RedisRateLimiterExample2 {

    public static void main(String[] args) throws InterruptedException {
        // 创建Redisson客户端
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.8.38:6379").setPassword("Jxkj@2022");
        RedissonClient redisson = Redisson.create(config);

        // 创建RateLimiter，每分钟生成1000个令牌
        RRateLimiter rateLimiter = redisson.getRateLimiter("myRateLimiter");
        rateLimiter.trySetRate(RateType.OVERALL, 1, 5, RateIntervalUnit.SECONDS);
        Thread.sleep(100);
        // 进行限流判断
//        ExecutorService es = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 2 ; i++) {
            if (rateLimiter.tryAcquire(1)) {
                long l = rateLimiter.availablePermits();
                // 请求通过，执行相应的业务逻辑
                System.out.println("API调用成功=========================="+l);
            } else {
                // 请求被限制，执行相应的处理逻辑
                System.out.println("API调用超过限制");
            }
            Thread.sleep(1000);
        }



        // 关闭Redisson客户端
        redisson.shutdown();
    }
}
